<template>
  <div class="dg-header-cell-wrapper" v-show="show"
       :style="cellWrapperStyle">
    <div class="dg-header-cell" :style="[cellStyle, column.headerStyle]" :class="[cellClass, column.headerClass]">
      <div class="dg-resize-bar-left" @mousedown="handleMouseDown($event, column)"
           v-if="leftResizable"></div>
      <div class="dg-check-all" v-if="hasSelectAll" :class="[verticalAlignClass]">
        <checkbox :value="checkAllState" @input="onCheckAllStateChange"></checkbox>
      </div>
      <div style="position: relative;width: 100%;height: 100%;" @click="handleSortClick($event,column)">
        <div class="dg-header-cell-content" :class="[verticalAlignClass, horizontalAlignClass, sort]">
          {{column.title}}
          <span class="caret-wrapper" v-if="column.sortable && !column.subColumns" @click="handleSortClick($event,column)">
            <i class="sort-caret ascending" @click="handleSortClick($event, column, 'ascending')"></i>
            <i class="sort-caret descending" @click="handleSortClick($event, column, 'descending')"></i>
          </span>
        </div>
      </div>
      <div class="dg-resize-bar" @mousedown="handleMouseDown($event, column)"
           v-if="normalResizable"></div>
    </div>
    <data-grid-header-cell v-for="col in column.subColumns"
                           @start-resize="handleMouseDown"
                           @check-all="onCheckAllStateChange"
                           :key="col.field"
                           :column="col"
                           :root-config="rootConfig"
                           :heights="heights"
                           :level="level + 1"></data-grid-header-cell>
  </div>
</template>

<script>
  import Checkbox from '../components/Checkbox.vue'
  import _ from 'lodash'

  export default {
    components: {Checkbox},
    name: 'DataGridHeaderCell',
    props: {
      rootConfig: {
        type: Object,
        default () {
          return {}
        }
      },
      column: {
        type: Object,
        default () {
          return {}
        }
      },
      level: Number,
      heights: {
        type: Array,
        default () {
          return []
        }
      }
    },
    data () {
      return {
        sort: '',
        show: false,
        width: 24,
        left: 0,
        currentDrag: null,
        checkAllState: false
      }
    },
    methods: {
      refreshPosition () {
        this.width = this.column._width
        this.left = this.column._left || 0
        this.show = !this.column.hide
      },
      handleMouseDown ($event, column) {
        let isRightFixed = this.rootColumn.fixed === 'right'
        this.$emit('start-resize', $event, column, isRightFixed)
      },
      setCheckAllState (isAllChecked) {
        this.checkAllState = isAllChecked
      },
      onCheckAllStateChange (isAllChecked) {
        this.$emit('check-all', isAllChecked)
      },
      handleSortClick (event, column, order) {
        let vm = this
        let itemName = vm.$parent.$parent.$el.id + 'sort'
        let columnArray = vm.$parent.rootConfig.columns
        event.stopPropagation()
        if (!column.sortable) return
        if (!column.order) {
          localStorage.setItem(itemName, JSON.stringify({
            'field': column.field,
            'order': order || 'ascending'
          }))
          column.order = order || 'ascending'
        } else {
          if (column.order === order) {
            localStorage.setItem(itemName, JSON.stringify({
              'field': column.field,
              'order': ''
            }))
            column.order = ''
          } else {
            if (column.order === 'ascending') {
              localStorage.setItem(itemName, JSON.stringify({
                'field': column.field,
                'order': 'descending'
              }))
              column.order = 'descending'
            } else {
              localStorage.setItem(itemName, JSON.stringify({
                'field': column.field,
                'order': order || ''
              }))
              column.order = order || ''
            }
          }
        }
        this.sort = column.order
        _.forEach(columnArray, col => {
          if (col.sortable && col.field !== column.field) {
            col._$headerVM.column.order = ''
            col._$headerVM.sort = ''
          }
        })
        this.$parent.$emit('sort-change')
      }
    },
    computed: {
      verticalAlignClass () {
        return this.rootConfig.titleVerticalAlign ? 'dg-abs-v-' + this.rootConfig.titleVerticalAlign : null
      },
      horizontalAlignClass () {
        return this.rootConfig.titleHorizontalAlign ? 'dg-text-' + this.rootConfig.titleHorizontalAlign : null
      },
      cellWrapperStyle () {
        return {
          width: `${this.width}px`,
          height: `${this.heights[this.level]}px`,
          bottom: '0',
          left: `${this.left}px`
        }
      },
      cellStyle () {
        return {
          height: `${this.isLeafCell ? this.heights[this.level] : (this.heights[this.level] - this.heights[this.level + 1])}px`,
          'padding-left': `${this.hasSelectAll ? '38px' : null}`
        }
      },
      cellClass () {
        return {
          'dg-header-top-border': !!this.column.borders[0],
          'dg-header-bottom-border': !!this.column.borders[2],
          'dg-header-left-border': !!this.column.borders[3],
          'dg-header-right-border': !!this.column.borders[1]
        }
      },
      isLeafCell () {
        return !this.column.subColumns || this.column.subColumns.length === 0
      },
      hasSelectAll () {
        return this.column.checkbox && this.column.checkAll && this.isLeafCell
      },
      resizable () {
        return this.column.resizable !== false && this.isLeafCell
      },
      rootColumn () {
        let rc = this.column
        while (rc.parent) {
          rc = rc.parent
        }
        return rc
      },
      leftResizable () {
        return this.resizable && this.rootColumn.fixed === 'right'
      },
      normalResizable () {
        return !this.leftResizable && this.resizable
      }
    },
    mounted () {
      this.column._$headerVM = this
      if (this.column.sortable) {
        console.log(this.$parent.$parent.$el.id)
        let itemName = this.$parent.$parent.$el.id + 'sort'
        let storageObj = JSON.parse(localStorage.getItem(itemName))
        if (localStorage.getItem(itemName)) {
          if (storageObj.field === this.column.field) {
            this.column.order = storageObj.order
            this.sort = this.column.order
          }
        }
      }
    },
    destroyed () {
      delete this.column._$headerVM
    }
  }
</script>

<style lang="scss">
  $header-cell-padding: 4px;

  .dg-header-cell-wrapper{
    position: absolute;
    left: 0;
    right: 0;
    overflow: hidden;
  }
  .dg-header-cell{
    background: #fff;
    position: relative;
    padding: $header-cell-padding;
    user-select: none;
  }
  .dg-abs-v-middle{
    top: 50%;
    transform: translateY(-50%);
  }
  .dg-abs-v-top{
    top: $header-cell-padding;
  }
  .dg-abs-v-bottom{
    bottom: $header-cell-padding;
  }
  .dg-text-center{
    text-align: center;
  }
  .dg-text-left{
    text-align: left;
  }
  .dg-text-right{
    text-align: right;
  }
  .dg-check-all{
    position: absolute;
    left: 8px;
    line-height: 0 !important;
  }
  .dg-header-cell-content{
    position: absolute;
    left: 0;
    width: 100%;
    .caret-wrapper {
      position: relative;
      cursor: pointer;
      display: inline-block;
      vertical-align: middle;
      margin-top: -2px;
      width: 16px;
      height: 30px;
      overflow: visible;
      overflow: initial;
      .sort-caret{
        display: inline-block;
        width: 0;
        height: 0;
        border: 0;
        content: "";
        position: absolute;
        z-index: 2;
      }
    }
    .sort-caret.ascending, .sort-caret.descending {
      border-right: 5px solid transparent;
      border-left: 5px solid transparent;
    }
    .sort-caret.ascending {
      top: 9px;
      border-top: none;
      border-bottom: 5px solid #97a8be;
    }
    .sort-caret.descending {
      bottom: 9px;
      border-top: 5px solid #97a8be;
      border-bottom: none;
    }
  }
  .ascending .sort-caret.ascending {
    border-bottom-color: #48576a;
  }
  .descending .sort-caret.descending {
    border-top-color: #48576a;
  }
  .dg-resize-bar{
    width: 4px;
    position: absolute;
    top: 0;
    right: 0;
    height: 100%;
    cursor: col-resize;
    /*background: #00b3ee;*/
  }
  .dg-resize-bar-left{
    width: 4px;
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    cursor: col-resize;
    /*background: #00b3ee;*/
  }
  .dg-header-top-border{
    border-top: solid 1px #DDD;
  }
  .dg-header-bottom-border{
    border-bottom: solid 1px #666;
  }
  .dg-header-left-border{
    border-left: solid 1px #DDD;
  }
  .dg-header-right-border{
    border-right: solid 1px #DDD;
  }
</style>
